package com.example.heipictureserver.controller;

import com.example.heipictureserver.annotation.AuthCheck;
import com.example.heipictureserver.common.BaseResponse;
import com.example.heipictureserver.common.ResultUtils;
import com.example.heipictureserver.constant.UserConstant;
import com.example.heipictureserver.exception.BusinessException;
import com.example.heipictureserver.exception.ErrorCode;
import com.example.heipictureserver.mangger.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/*
 *@Description 类功能简要描述
 *@Author bwg
 *@Date 2025/1/19 10:47
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {
 private final CosManager cosManager;

 public FileController(CosManager cosManager) {
  this.cosManager = cosManager;
 }
 @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
 @PostMapping("/test/upload")
 public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile file) {
  String filename = file.getOriginalFilename();
  String filepath = String.format("/test/%s", filename);
  File tempfile = null;
  try {
   // 上传文件
   tempfile = File.createTempFile(filepath, null);
   file.transferTo(tempfile);
   cosManager.putObject(filepath, tempfile);
   // 返回可访问的地址
   return ResultUtils.success(filepath);
  } catch (Exception e) {
      log.error("file upload error, filepath = {}", filepath, e);
   throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
  } finally {
      // 删除临时文件
      boolean delete = false;
      if (tempfile != null) {
          delete = tempfile.delete();
      }
      if (!delete) {
    log.error("file delete error, filepath = {}", filepath);
   }
  }
 }

    /**
     *
     * @param filepath
     * @param response
     * @throws IOException
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download/")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            // 释放流
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }

    }
}
